package web;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class WebApps {
    private String appsBase;
    private File appsBaseFile;
    private List<WebApp> webApps = new ArrayList<>();

    public String getAppsBase() {
        return appsBase;
    }

    public void setAppsBase(String appsBase) {
        this.appsBase = appsBase;
    }

    public List<WebApp> getWebApps() {
        return webApps;
    }

    public void setWebApps(List<WebApp> webApps) {
        this.webApps = webApps;
    }

    public WebApps(String appsBase) {
        this.appsBase = appsBase;
        this.appsBaseFile = new File(this.appsBase);
        System.out.println("appsBase: " + appsBase);
        System.out.println("appsBase abs dir: " + this.appsBaseFile.getAbsolutePath());

        scanWebApps(this.appsBaseFile);
    }

    private boolean isWebAppDirectory(File dirFile) {
        if (dirFile.isDirectory()) {
            for (File file: dirFile.listFiles()) {
                if (file.getName().equals("web.xml") && file.isFile()) {
                    return true;
                }
            }
        }
        return false;
    }

    // 扫描appsBase下的所有目录
    private void scanWebApps(File file) {
        if (file.isDirectory()) {
            if (isWebAppDirectory(file)) {
//                System.out.println(file.getAbsolutePath());
                WebApp webApp = new WebApp(this.appsBaseFile, file);
                webApps.add(webApp);
            }

            for (File subFile: file.listFiles()) {
                scanWebApps(subFile);
            }
        }
    }

    public static void main(String[] args) {
        WebApps webApps = new WebApps("/Users/zhangliang/webapps");

        for (WebApp webApp: webApps.getWebApps()) {
            System.out.println(webApp.getContextPath() + " " + webApp.getAbsoluteAppBase());
        }
    }
}
